package com.baosu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baosu.domain.Result;
import com.baosu.domain.User;
import com.baosu.service.UserService;
import com.baosu.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Override
    public Result login(HttpServletRequest request, User user) {
        String username = user.getUsername();
        String password = user.getPassword();

        // 根据用户名username查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        User u = this.getOne(queryWrapper);

        // 没有查询到则返回登录失败
        if(u == null){
            return Result.fail(null).message("用户名或密码错误");
        }

        // 密码不一致则返回登录失败结果
        if(!u.getPassword().equals(password)){
            return Result.fail(null).message("用户名或密码错误");
        }

        // 登录成功，将员工id存入Session，并返回登录成功
        request.getSession().setAttribute("user",u.getId());
        return Result.ok(u.getUsername()).message("登录成功");
    }

    @Autowired
    private HttpServletRequest request;

    @Override
    public Result updatePwd(String oldPwd, String newPwd) {
        Integer userId = (Integer) request.getSession().getAttribute("user");
        // 根据用户ID查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,userId);
        User user = this.getOne(queryWrapper);

        // 没有查询到用户
        if(user == null){
            return Result.fail(null).message("请登录");
        }
        // 原密码错误
        System.out.println("user = " + user);
        System.out.println("oldPwd = " + oldPwd);
        System.out.println("newPwd = " + newPwd);
        if(!user.getPassword().equals(oldPwd)){
            return Result.fail(null).message("原密码错误");
        }

        User user2 = new User();
        user2.setId(userId);
        user2.setPassword(newPwd);
        this.updateById(user2);

        return Result.ok(null).message("密码修改成功");
    }

}




